package com.maori.languageapp.bookmarks;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.maori.languageapp.LanguageAppCaptureActivity;
import com.maori.languageapp.R;
import com.maori.languageapp.consts.JSONfunctions;
import com.maori.languageapp.consts.UrlContant;
import com.maori.languageapp.subview.Maori_BookMark_Items;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class Languageapp_Bookmarks extends Activity {
	
	TextView txtHeading;
	ProgressDialog mProgressDialog;
	EditText searchfiltertext;
	String getDiscoverWordsListURL,LastDownloadUpdateTime,BookMarkRefId,result,node_category;
	JSONObject jsonobject,jsonobjectres;
	JSONArray jsonarray;
	ListView listview;
	int NCMID;
	int timeoutConnection = 5000;
	InputStream is = null;
	StringBuilder sb = null;
	JSONArray jArray;
	HttpParams httpParameters = new BasicHttpParams();
	Languageapp_Bookmarks_Adapter adapter;
	ArrayList<HashMap<String, String>> arraylist;
	LinearLayout checkemptylist,listingNodeDetails;
	Button navigateToCapture;
	int listCounter = 0;
	
	/************Adapter Constant Variables****************/
	private static String MID = "MID";
	private static String NID = "NID";
	private static String word = "word";
	private static String wordb = "wordb";
	private static String M_Source = "M_Source";
	private static String NCMIDStr = "NCMIDStr";
	private static String first_name = "first_name";
	private static String last_name = "last_name";
	private static String tribe = "tribe";
	private static String userimage = "userimage";

	private static String TotalsLikes = "TotalsLikes";
	private static String TotalsSynonim = "TotalsSynonim";
	private static String TotalImages = "TotalImages";
	private static String TotalAudios = "TotalAudios";
	private static String TotalVideos = "TotalVideos";
	
	private static String UserNodeBookMarked = "UserNodeBookMarked";
	private static String node_dif_audio_url = "node_dif_audio_url";
	private static String MAINUID = "MAINUID";
	private static String UserLikedForNode = "UserLikedForNode";
	
	
	String CurrentUID;
	
	private SQLiteDatabase mydb;
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	private static final String TAG = null;
	String AudioURL;
	int NodeAudioPlay = 0;
	private MediaPlayer mediaPlayer;
	//navigateToCapture
	public void navigateToCapture(View view) {
		Intent i = new Intent(getApplicationContext(),
				LanguageAppCaptureActivity.class);
		int MEDIAID = Integer.parseInt(NCMIDStr);
		i.putExtra("NCMID", MEDIAID);
		i.putExtra("node_category",node_category);
		i.putExtra("type", "Word");
		i.putExtra("SEARCHKEY", "00/00/00/00/00");
		i.putExtra("ACTIVE", "1");
		startActivity(i);
		Log.e(NCMIDStr," =" + NCMIDStr);
		Log.e("NCMID", " ="+ NCMIDStr);
		Log.e("CATEG", " ="+ node_category);
	}
	
	public void btnBackAction(View view) {
		Languageapp_Bookmarks.this.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}
	
	@Override
	public void onBackPressed() {
		Languageapp_Bookmarks.this.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}
	
	
	public void PlayDefaultAudio(View view) {
		Button des = (Button) view;
		AudioURL = des.getText().toString();
	
		if(NodeAudioPlay == 0){
			NodeAudioPlay = 1;
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			try {
				mediaPlayer.setDataSource(AudioURL);
				mediaPlayer.prepare();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			mediaPlayer.start();
			Log.e("########", "Audio Recording Play Start...");
			// Audio Complete Identification
			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				public void onCompletion(MediaPlayer mp) {
					mediaPlayer.stop();
					mediaPlayer.reset();
					NodeAudioPlay = 0;
					Log.e("########", "Audio Play Completed...");
				}
			});
		}
		
		
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.maori_discover_list_panel);
		
		txtHeading  =  (TextView) findViewById(R.id.screenTitle);
		txtHeading.setText("My Bookmarks");
		
		
		searchfiltertext  =  (EditText) findViewById(R.id.searchfiltertext);
		
		searchfiltertext.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				String text = searchfiltertext.getText().toString().toLowerCase(Locale.getDefault());
				//adapter.filter(text);
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
			}
		});
		
		
		/**********Calling URL*************/
		getDiscoverWordsListURL = UrlContant.getDiscoverWordsList;
		
		checkemptylist =  (LinearLayout) findViewById(R.id.checkemptylist);
		listingNodeDetails =  (LinearLayout) findViewById(R.id.listingNodeDetails);
		navigateToCapture =  (Button) findViewById(R.id.navigateToCapture);
		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			 NCMIDStr  = extras.getString("NCMID"); 
			 node_category = extras.getString("node_category");
			 Log.e(TAG, "******DJ NCMIDStr 1:" + NCMIDStr);
		}
		
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterUserInfo = new ContentValues();
		Cursor readUserDetails = null;
		try {
			String queryCheckUsers = "SELECT * FROM User Where Activate = '1'";
			readUserDetails = mydb.rawQuery(queryCheckUsers, null);
		} catch (Exception e) {

		}
		if (readUserDetails != null) {
			if (readUserDetails.getCount() > 0) {
				while (readUserDetails.moveToNext()) {
					CurrentUID = readUserDetails.getString(11);
				}
			}
			else{
				CurrentUID = "1";
			}
		}
		mydb.close();
		
		new DownloadJSON().execute();
	}
	
	
	// DownloadJSON AsyncTask
		private class DownloadJSON extends AsyncTask<Void, Void, Void> {

			private final String TAG = null;


			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// Create a progressdialog
				mProgressDialog = new ProgressDialog(Languageapp_Bookmarks.this);
				// Set progressdialog title
				mProgressDialog.setTitle("Loading");
				// Set progressdialog message
				mProgressDialog.setMessage("Loading Words Details..");
				mProgressDialog.setIndeterminate(false);
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				mProgressDialog.setCancelable(false);
				// Show progressdialog
				mProgressDialog.show();
			}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/getUsersBookMarkRecords.php");
				JSONObject json = new JSONObject();
				json.put("record1", CurrentUID);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "request MID**** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {
					BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						Log.e("REQUEST :", "PRINT WORDS = " + result);
						arraylist = new ArrayList<HashMap<String, String>>();
						try {
							JSONObject jsonObj = new JSONObject(result);
							jsonarray = jsonObj.getJSONArray("posts");
							for (int i = 0; i < jsonarray.length(); i++) {
								JSONObject c = jsonarray.getJSONObject(i);
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("word", c.getString("word"));
								map.put("wordb", c.getString("wordb"));
								map.put("NID", c.getString("NID"));
								map.put("M_Source", c.getString("M_Source"));
								map.put("MID", c.getString("MID"));
								map.put("first_name", c.getString("first_name"));
								map.put("last_name", c.getString("last_name"));
								map.put("tribe", c.getString("tribe"));
								map.put("userimage", c.getString("userimage"));
								map.put("TotalsLikes", c.getString("TotalsLikes"));
								map.put("TotalsSynonim", c.getString("TotalsSynonim"));
								map.put("TotalImages", c.getString("TotalImages"));
								map.put("TotalAudios", c.getString("TotalAudios"));
								map.put("TotalVideos", c.getString("TotalVideos"));
								map.put("TotalVideos", c.getString("TotalVideos"));
								map.put("UserNodeBookMarked", c.getString("UserNodeBookMarked"));
								map.put("node_dif_audio_url", c.getString("node_dif_audio_url"));
								map.put("UserLikedForNode", c.getString("UserLikedForNode"));
								map.put("MAINUID", c.getString("MAINUID"));
								// Set the JSON Objects into the array
								arraylist.add(map);
								listCounter = listCounter + 1;
							}
						}
						catch (Exception e) {
							Log.v(TAG, "***** Exception *****:" + e);
						}
					}

				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			if(listCounter >= 1) {
				listingNodeDetails.setVisibility(LinearLayout.VISIBLE);
				checkemptylist.setVisibility(LinearLayout.GONE);
				// Locate the listview in listview_main.xml
				listview = (ListView) findViewById(R.id.listviewdiscover);
				// Pass the results into ListViewAdapter.java
				adapter = new Languageapp_Bookmarks_Adapter(Languageapp_Bookmarks.this,
						arraylist);
				// Binds the Adapter to the ListView
				listview.setAdapter(adapter);
			}
			else {
				listingNodeDetails.setVisibility(LinearLayout.GONE);
				checkemptylist.setVisibility(LinearLayout.VISIBLE);
				navigateToCapture.setText("No Records Found In This Category");
				navigateToCapture.setCompoundDrawablesWithIntrinsicBounds(0,
						0, 0, R.drawable.capture_word);
			}
			// Close the progressdialog
			mProgressDialog.dismiss();
		}
		}
		
		//***********Memory Handling****************
		@Override
		   protected void onStop(){
		      super.onStop();
		   }

		   //Fires after the OnStop() state
		   @Override
		   protected void onDestroy() {
		      super.onDestroy();
		      try {
		         trimCache(this);
		      } catch (Exception e) {
		         // TODO Auto-generated catch block
		         e.printStackTrace();
		      }
		   }

		   public static void trimCache(Context context) {
		      try {
		         File dir = context.getCacheDir();
		         if (dir != null && dir.isDirectory()) {
		            deleteDir(dir);
		         }
		      } catch (Exception e) {
		         // TODO: handle exception
		      }
		   }

		   public static boolean deleteDir(File dir) {
		      if (dir != null && dir.isDirectory()) {
		         String[] children = dir.list();
		         for (int i = 0; i < children.length; i++) {
		            boolean success = deleteDir(new File(dir, children[i]));
		            if (!success) {
		               return false;
		            }
		         }
		      }

		      // The directory is now empty so delete it
		      return dir.delete();
		   }

		   
		   
		/****************Getters and Setters*****************************/
		public static String getWord() {
			return word;
		}

		public static void setWord(String word) {
			Languageapp_Bookmarks.word = word;
		}

		public static String getWordb() {
			return wordb;
		}

		public static void setWordb(String wordb) {
			Languageapp_Bookmarks.wordb = wordb;
		}

		public static String getTotalsSynonim() {
			return TotalsSynonim;
		}

		public static void setTotalsSynonim(String totalsSynonim) {
			TotalsSynonim = totalsSynonim;
		}

		public static String getTotalAudios() {
			return TotalAudios;
		}

		public static void setTotalAudios(String totalAudios) {
			TotalAudios = totalAudios;
		}

		public static String getTotalImages() {
			return TotalImages;
		}

		public static void setTotalImages(String totalImages) {
			TotalImages = totalImages;
		}

		public static String getTotalVideos() {
			return TotalVideos;
		}

		public static void setTotalVideos(String totalVideos) {
			TotalVideos = totalVideos;
		}

		public static String getTotalsLikes() {
			return TotalsLikes;
		}

		public static void setTotalsLikes(String totalsLikes) {
			TotalsLikes = totalsLikes;
		}

		public static String getUserNodeBookMarked() {
			return UserNodeBookMarked;
		}

		public static void setUserNodeBookMarked(String userNodeBookMarked) {
			UserNodeBookMarked = userNodeBookMarked;
		}

		public static String getNode_dif_audio_url() {
			return node_dif_audio_url;
		}

		public static void setNode_dif_audio_url(String node_dif_audio_url) {
			Languageapp_Bookmarks.node_dif_audio_url = node_dif_audio_url;
		}

		public static String getM_Source() {
			return M_Source;
		}

		public static void setM_Source(String m_Source) {
			M_Source = m_Source;
		}

		public static String getNID() {
			return NID;
		}

		public static void setNID(String nID) {
			NID = nID;
		}

		public static String getMID() {
			return MID;
		}

		public static void setMID(String mID) {
			MID = mID;
		}

		public static String getFirst_name() {
			return first_name;
		}

		public static void setFirst_name(String first_name) {
			Languageapp_Bookmarks.first_name = first_name;
		}

		public static String getLast_name() {
			return last_name;
		}

		public static void setLast_name(String last_name) {
			Languageapp_Bookmarks.last_name = last_name;
		}

		public static String getTribe() {
			return tribe;
		}

		public static void setTribe(String tribe) {
			Languageapp_Bookmarks.tribe = tribe;
		}

		public static String getUserimage() {
			return userimage;
		}

		public static void setUserimage(String userimage) {
			Languageapp_Bookmarks.userimage = userimage;
		}

		public static String getMAINUID() {
			return MAINUID;
		}

		public static void setMAINUID(String mAINUID) {
			MAINUID = mAINUID;
		}

		public static String getUserLikedForNode() {
			return UserLikedForNode;
		}

		public static void setUserLikedForNode(String userLikedForNode) {
			UserLikedForNode = userLikedForNode;
		}
}
